// src\components\App\App.jsx
import React, { useState, useEffect } from 'react';
import { v4 as uuidv4 } from 'uuid';
import BmiForm from '../BmiForm/BmiForm';
import Bar from '../Bar/Bar';
import Info from '../Info/Info';
import 'materialize-css/dist/css/materialize.min.css';
import './App.css'
import { getData, storeData } from '../../helpers/localStorage';



const App = () => {
  // ，initialState 被定义为一个箭头函数，然后作为 useState 的参数使用。这里有一个常见的误解：通常我们不希望将 useState 的初始化函数定义为箭头函数，因为这样会导致每次组件渲染时都会创建一个新的函数实例，可能会引发不必要的组件重新渲染。
  // initialState是一个箭头函数，这种方式适用于当你想延迟执行 getData('data') 或者在未来的某个时间点决定是否执行这个操作时

  const initialState = () => getData('data') || [];

  const [state, setState] = useState(initialState)
  const [data, setData] = useState({});


  const Input_handleChange = val => {
    let heightInM = val.height / 100;
    val.bmi = (val.weight / (heightInM * heightInM)).toFixed(2);
    val.id = uuidv4();  // 生成唯一id
    let newVal = [...state, val];
    let len = newVal.length;
    if (len > 7) newVal = newVal.slice();
    setState(newVal);
    // console.log('App_state', state)
  }





  // let lastState // 注意这个地方，如只是一般的变量，那么每次setState(lastState),渲染的时候handleUndo函数都会从新执行，一直在初始化lastState，所以需要使用useRef
  // let lastState = useRef([])
  const deleteCard = (id) => {
    storeData('lastState', state);  // 不使用useRef([])缓存了，直接本地化保存数据
    let newState = state.filter(item => item.id !== id)
    setState(newState)
    // console.log(id,state)
    // console.log(lastState.current)
  }

  const handleUndo = () => {
    // setState(lastState);
    setState(getData('lastState'));
    // console.log(lastState.current , state)
  }

  useEffect(() => {
    storeData('data', state);  // 初始化组件和每次更新state时，都会触发storeData保存数据
    // 交给图表 显示数据
    const date = state.map(item => item.date)
    const bmi = state.map(item => item.bmi)
    let newData = { date, bmi };
    setData(newData);
    // console.log('App_state', state)

  }, [state]);


  return (
    <div className='container'>
      {/* 标题 */}
      <div className='row center'>
        <h1 className='white-text'>BMI Tracker</h1>
      </div>
      < div className='row' >
        <div className='col m12 s12'>
          {/* 输入框 */}
          <BmiForm Input_handleChange={Input_handleChange} />
          {/* 使用折线图 */}
          <Bar labelData={data.date} bmiData={data.bmi} />
          {/* 详细记录信息 */}
          <div>
            <div className='row center'>
              <h2 className='white-text'>7 Day Data</h2>
            </div>

            <div className='data-container row'>
              {state.length > 0 ? (
                <>
                  {state.map(info => (
                    <Info
                      key={info.id}
                      weight={info.weight}
                      height={info.height}
                      id={info.id}
                      date={info.date}
                      bmi={info.bmi}
                      deleteCard={deleteCard}
                    />
                  ))}
                </>
              ) : (<div className='center white-text'>No log found</div>)}
            </div>
          </div>
          {getData('lastState') !== null ? (
            <div className='center'>
              <button className='calculate-btn' onClick={handleUndo}>Undo</button>
            </div>
          ) : ('')}


          <div className='center'>
            <p style={{ color: '#fff', fontSize: '24px' }} >{state.map(item => item.weight).join('--')}</p>
          </div>
        </div>
      </div>
    </div>
  )
};
export default App;